import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout, getInfo } from '@/api/login'
Vue.use(Vuex)

const store = new Vuex.Store({
  state:{
    user:{
      token: getToken(),
      name: '',
      avatar: '',
      roleType:'',
    }
  },
    getters:{
      token: state => state.user.token,
      name:state => state.user.name,
      roleType:state => state.user.roleType,
      avatar:state => state.user.avatar,
  },
  mutations:{
      SET_TOKEN: (state, token) => {
          state.user.token = token
      },
      SET_NAME: (state, name) => {
          state.user.name = name
      },
      SET_AVATAR: (state, avatar) => {
          state.user.avatar = avatar
      },
      SET_ROLE_TYPE: (state, roleType) => {
          state.user.roleType = roleType
      },
  },
  actions:{
      // 自带的
      // 登录
      Login({ commit }, userInfo) {
          const username = userInfo.username.trim()
          const password = userInfo.password

          return new Promise((resolve, reject) => {
              login(username, password).then(res => {
                  setToken(res)
                  commit('SET_TOKEN', res)
                  resolve()
              }).catch(error => {
                  reject(error)
              })
          })
      },
      // 获取用户信息
      GetInfo({ commit, state }) {
          return new Promise((resolve, reject) => {
              getInfo().then(res => {
                  const avatar = (res.avatar == "" || res.avatar == null) ? require("@/assets/images/profile.jpg") : res.avatar;
                  commit('SET_ROLE_TYPE', res.roleType)
                  commit('SET_NAME', res.nickName)
                  commit('SET_AVATAR', avatar)
                  resolve(res)
              }).catch(error => {
                  reject(error)
              })
          })
      },
      // 退出系统
      LogOut({ commit, state }) {
          return new Promise((resolve, reject) => {
              logout(state.token).then(() => {
                  commit('SET_TOKEN', '')
                  commit('SET_ROLE_TYPE', '')
                  removeToken()
                  resolve()
              }).catch(error => {
                  reject(error)
              })
          })
      },
  }
})

export default store
